import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { useUserStoreHook } from "@/store/modules/user";

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStoreHook();
    if (userStore.token) {
      config.headers.Authorization = userStore.token;
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, msg } = response.data;
    if (code === 200 || code === "00000") {
      return response.data;
    }
    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer) {
      return response;
    }

    ElMessage.error(msg || "系统出错");
    return Promise.reject(new Error(msg || "Error"));
  },
  (error: any) => {
    console.log(error);
    if (error.response.data) {
      const { code, msg } = error.response.data;
      // token 过期,重新登录
      if (code === 10001) {
        ElMessageBox.confirm("当前页面已失效，请重新登录", "提示", {
          confirmButtonText: "确定",
          type: "warning",
        }).then(() => {
          const userStore = useUserStoreHook();
          userStore.resetToken().then(() => {
            location.reload();
          });
        });
      } else {
        ElMessage.error(msg || "系统出错");
      }
    }
    return Promise.reject(error.message);
  }
);

/**
 * 上传
 * @param url
 * @param data
 */
export function upload(url, file, data) {
  const formData = new FormData();
  formData.append("file", file);

  // 附加数据
  if (data) {
    Object.keys(data).forEach((key) => {
      formData.append(key, data[key]);
    });
  }

  return new Promise((resolve, reject) => {
    // 打开
    const loading = Loading.service({
      text: "正在上传数据...",
      background: "rgba(0, 0, 0, 0.7)",
    });

    service
      .request({
        url: url,
        method: "post",
        data: formData,
        timeout: 1200000,
      })
      .then((response) => {
        console.log(response);
        loading.close();
        resolve(response);
      })
      .catch((err) => {
        loading.close();
        reject(err);
      });
  });
}

/**
 * 下载
 * @param url
 * @param data
 */
export function download(url, data, fileName) {
  return new Promise((resolve, reject) => {
    // 打开
    const loading = Loading.service({
      text: "正在下载数据...",
      background: "rgba(0, 0, 0, 0.7)",
    });

    service
      .request({
        url: url,
        method: "post",
        data: data,
        timeout: 1200000,
        responseType: "blob",
      })
      .then((res) => {
        loading.close();

        // 文件下载
        const blob = new Blob([res.data], {
          type: "application/vnd.ms-excel",
        });

        // 获得文件名称
        let link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.setAttribute("download", fileName);
        link.click();
        link = null;
        Message.success("导出成功!");
      })
      .catch((err) => {
        loading.close();
        reject(err);
      });
  });
}

// /**
//  * 封装post请求
//  * @param url
//  * @param data
//  * @returns {Promise}
//  */
// export function post(url, data = {}) {
//   return new Promise((resolve, reject) => {
//     service.post(url, data).then(
//       (response) => {
//         resolve(response);
//       },
//       (err) => {
//         reject(err);
//       }
//     );
//   });
// }

/**
 * 封装post请求
 * @param url 请求的URL
 * @param data 请求的数据
 * @returns 返回一个 Promise 对象
 */
export function post(url: string, data: any = {}): Promise<AxiosResponse> {
  return new Promise<AxiosResponse>((resolve, reject) => {
    service.post(url, data).then(
      (response: AxiosResponse) => {
        resolve(response);
      },
      (err: any) => {
        reject(err);
      }
    );
  });
}

// 导出 axios 实例
export default service;
